package com.hjt.gulimall.member.interceptor;

import com.hjt.common.constant.AuthConstant;
import com.hjt.common.to.member.UserLoginTo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author:97007
 * @date:2021/10/9 17:28
 */
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserLoginTo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 对远程调用不拦截
        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if (match) {
            return true;
        }

        HttpSession session = request.getSession();
        UserLoginTo attribute = (UserLoginTo) session.getAttribute(AuthConstant.LOGIN_USER);
        if (attribute != null) {
            // 已登录
            loginUser.set(attribute);
            return true;
        } else {
            // 未登录
            response.sendRedirect("http://auth.gulimall.com");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
